package com.dede.applib.extends

import android.app.Activity
import android.app.Fragment
import android.content.Context
import android.content.Intent
import android.graphics.drawable.Drawable
import android.os.Build
import android.support.annotation.ColorRes
import android.support.annotation.DrawableRes
import android.support.annotation.StringRes
import android.support.v4.content.ContextCompat

/**
 * @author hsh
 * @time 2017/7/15 015 上午 11:38.
 * @doc
 */
fun Context.color(@ColorRes id: Int): Int = ContextCompat.getColor(this, id)

fun Context.drawable(@DrawableRes id: Int): Drawable = ContextCompat.getDrawable(this, id)

fun Context.string(@StringRes id: Int): String = getString(id)



fun Activity.context(): Context = this

fun Fragment.context(): Context {
    return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        this.context
    } else {
        this.activity
    }
}

fun android.support.v4.app.Fragment.context(): Context {
    return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        this.context
    } else {
        this.activity
    }
}


fun Context.startActivity(packageName: String, className: String) {
    startActivity(packageName, className, null)
}

fun Context.startActivity(packageName: String, className: String, callBack: ((Exception) -> Unit?)? = null) {
    startActivity(getIntent(packageName, className), callBack)
}

fun Context.getIntent(packageName: String, className: String): Intent {
    val intent = Intent(Intent.ACTION_VIEW)
    return intent.setClassName(packageName, className)
}

fun Context.startActivity(intent: Intent, callBack: ((Exception) -> Unit?)? = null) {
    try {
        startActivity(intent)
    } catch (e: Exception) {
        callBack?.invoke(e)
        e.printStackTrace()
    }
}


fun Fragment.startActivity(packageName: String, className: String) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
        context.startActivity(packageName, className)
    else
        activity.startActivity(packageName, className)
}

fun Fragment.startActivity(packageName: String, className: String, callBack: ((Exception) -> Unit?)? = null) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
        context.startActivity(packageName, className, callBack)
    else
        activity.startActivity(packageName, className, callBack)
}

fun Fragment.startActivity(intent: Intent, callBack: ((Exception) -> Unit?)? = null) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
        context.startActivity(intent, callBack)
    else
        activity.startActivity(intent, callBack)
}

fun Fragment.getIntent(packageName: String, className: String): Intent {
    return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
        context.getIntent(packageName, className)
    else
        activity.getIntent(packageName, className)
}
